using System;
using System.Collections.Generic;
using GGEditor.API;

namespace GGEditor.Core.Plugins
{
	public class PluginNodeBuilder : IPluginNode
	{
		private readonly IList<IPluginNode> nodes = new List<IPluginNode>();
		private readonly IDictionary<string, IPluginNode> nodesByName =
			new Dictionary<string, IPluginNode>();

		public PluginNodeBuilder()
		{
			Condition = delegate { return PluginNodeState.Enabled; };
		}

		#region Implementation of IPluginNode

		public IPlugin Plugin { get; set; }

		public string Path
		{
			get
			{
				if (Parent == null)
					return "/";
				return PluginPaths.Join(Parent.Path, Name);
			}
		}

		public IPluginNode Parent { get; set; }

		public string Name { get; set; }

		public string Class { get; set; }

		public PluginNodeState State
		{
			get { return Condition(this); }
		}

		public PluginNodeConditionDelegate Condition { get; set; }

		public object Object { get; set; }

		public IEnumerable<IPluginNode> Nodes
		{
			get { return nodes; }
		}

		public IPluginNode GetChildNode(string name)
		{
			if (!nodesByName.ContainsKey(name))
				return null;
			return nodesByName[name];
		}

		public void AddChild(IPluginNode child)
		{
			nodes.Add(child);
			nodesByName[child.Name] = child;
			ChildAdded(this, child, nodes.Count-1);
		}

		public void InsertChild(IPluginNode child, int position)
		{
			nodes.Insert(position, child);
			nodesByName[child.Name] = child;
			ChildAdded(this, child, position);
		}

		public void RemoveChild(IPluginNode child)
		{
			int position = nodes.IndexOf(child);
			nodesByName.Remove(child.Name);
			nodes.Remove(child);
			ChildRemoved(this, child, position);
		}

		public event PluginNodeEventHandler ChildAdded = delegate { };

		public event PluginNodeEventHandler ChildRemoved = delegate { };

		void IPluginNode.Update()
		{
			
		}

		#endregion
	}
}